package pl.edu.uj.tcs.blef.protocol;

import java.io.PrintWriter;
import java.net.Socket;

import pl.edu.uj.tcs.blef.server.Client;
import pl.edu.uj.tcs.blef.server.Table;

public class JoinRequestHandler extends AbstractTableHandler {

	public JoinRequestHandler(Table table) {
		super(table);
	}

	@Override
	public void handle(Request request, Socket socket) {
		System.out.println("Handling " + request.message + " request from " + socket.getInetAddress().getHostAddress());
		JoinRequest ctr = (JoinRequest)request;
		
		String[] param = new String[2];
		param[0] = ctr.getPlayerNick();
		param[1] = socket.getInetAddress().getHostAddress();
		try {
			Client newClient = new Client(ctr.getPlayerNick(), socket, 1);
			if(table.getAwaitingPlayers().contains(newClient) ||
					table.getPlayers().contains(newClient)){
				
				Request r = new InvalidParametersErrorFactory().build(null, new NullRequestHandler());
				r.send(new PrintWriter(socket.getOutputStream()));
				
			} else {
				table.getIncomingPlayers().add(newClient);
				Request r = new RequestRequestFactory().build(param, new NullRequestHandler());
				r.send(new PrintWriter(table.getOperator().getSocket().getOutputStream()));
			} 
		} catch (Exception e){}
	}
}
